package com.yhy.admin.service;

import com.google.common.collect.Maps;
import com.yhy.admin.dto.SysCustomFieldDTO;
import com.yhy.common.vo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yhy.admin.dao.SysCustomFieldDao;
import com.yhy.admin.vo.SysCustomFieldVO;
import com.yhy.common.service.BaseService;

import java.util.List;
import java.util.Map;

/*
 *
 *  * *
 *  *  * <br>
 *  *  * <b>功能：</b><br>
 *  *  * <b>作者：</b>yanghuiyaun<br>
 *  *  * <b>日期：</b> 20-4-24 上午9:12 <br>
 *  *  * <b>版权所有：<b>版权所有(C) 2020<br>
 *  *
 *
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class SysCustomFieldService extends BaseService<SysCustomFieldVO> {

	@Autowired
	private  SysCustomFieldDao sysCustomFieldDao;

	@Override
	protected SysCustomFieldDao getDao() {
		return sysCustomFieldDao;
	}

	public List<SysCustomFieldVO> findByGridIdAndUser(String gridId, String userAccount, String sysOwnerCpy) {
		SysCustomFieldVO paramBean = new SysCustomFieldVO();
		paramBean.setEnableFlag("Y");
		paramBean.setGridId(gridId);
		paramBean.setCreateBy(userAccount);
		paramBean.setSysOwnerCpy(sysOwnerCpy);
		return findBy(paramBean);
	}

	public void deleteByGridIdAndUser(String gridId, String userAccount, String sysOwnerCpy) {
		SysCustomFieldVO paramBean = new SysCustomFieldVO();
		paramBean.setEnableFlag("Y");
		paramBean.setGridId(gridId);
		paramBean.setCreateBy(userAccount);
		paramBean.setSysOwnerCpy(sysOwnerCpy);
		this.deleteBy(paramBean);
	}

	public void saveCustomField(SysCustomFieldDTO customFieldDTO) {
		SysUser sysUser = customFieldDTO.getSysUser();
		SysCustomFieldVO paramBean = customFieldDTO.getParamBean();
		List<SysCustomFieldVO> fieldVOList = customFieldDTO.getCustomFieldList();

		String gridId = paramBean.getGridId();

		Map<String, String> existsIdMap = Maps.newHashMap();
		List<SysCustomFieldVO> existsFieldVOS = this.findByGridIdAndUser(gridId, sysUser.getUserAccount(), sysUser.getCpyCode());
		existsFieldVOS.stream().forEach(tmpvo -> {
			existsIdMap.put(tmpvo.getFieldProp(), tmpvo.getId());
		});
		for (SysCustomFieldVO tmpvo : fieldVOList) {
			tmpvo.setGridId(gridId);
			tmpvo.setEnableFlag("Y");
			tmpvo.setSysOwnerCpy(sysUser.getCpyCode());
			tmpvo.setCreateBy(sysUser.getUserAccount());

			if (existsIdMap.containsKey(tmpvo.getFieldProp())) {
				tmpvo.setId(existsIdMap.get(tmpvo.getFieldProp()));
				existsIdMap.remove(tmpvo.getFieldProp());
				this.update(tmpvo);
				continue;
			}
			this.insert(tmpvo);
		}
		for (String pkid : existsIdMap.values()) {
			SysCustomFieldVO deleteVo = new SysCustomFieldVO();
			deleteVo.setId(pkid);
			this.deleteById(deleteVo);
		}
	}

}
